package com.commit.controller;

import com.commit.domain.User;
import com.commit.service.UserService;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author:zyh
 * @Time:2021-02-27-18:50
 * @email:1269231889@qq.com
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    //注册页面
    @GetMapping("/registerPage")
    public String registerPage(){
        return "register";
    }
    //登录请求
    @RequestMapping("/login")
    public String login(HttpServletRequest request) throws Exception{
        // shiro在认证过程中出现错误后将异常类路径通过request返回
        String exceptionClassName = (String) request
                .getAttribute("shiroLoginFailure");
        if(exceptionClassName!=null){
            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
                throw new Exception("账号不存在");
            } else if (IncorrectCredentialsException.class.getName().equals(
                    exceptionClassName)) {
                throw new Exception("用户名/密码错误");
            } else{
                throw new Exception("error");//最终在异常处理器生成未知错误
            }
        }
        return "login";
    }
    //注册请求
    @ResponseBody
    @RequestMapping("/register")
    public String register(User user){
        user.setCreateTime(new Date());
        userService.register(user);
        return "success";
    }
}
